import React, { useState, useRef, useEffect } from 'react';
import { Button, Icon, Avatar, message, Modal, Spin, Tabs } from 'antd';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { useRequest, useInViewport } from '@umijs/hooks';
import TreeControlled from '@/components/blocks/TreeControlled';
import styles from './index.less';
import Detail from './components/Detail';
import Edit from './components/Edit';
import { Typography } from 'antd';
import {
  getUserList,
  manualSyncUser,
  resetPasswords,
  updateUserLockState,
  updateUserState,
  getDepartmentTreeByRole,
} from './service';
import AuthComponent from '@/components/Authorized/AuthComponent';

const { Paragraph } = Typography;
const TableList = () => {
  const [detailVisible, setDetailVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState(false);
  const [editUser, setEditUser] = useState(false);
  const searchRef = useRef();
  const [selectedKeys, setSelectedKeys] = useState([]);
  // 用于重置缓存页面的tab选中状态
  const inViewPort = useInViewport(() => document.querySelector('#pageViewId'));

  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 365);
    } else {
      controlH(document.body.clientHeight - 421);
    }
  }, [isCollapse])

  const reloadTable = function reloadTable() {
    if (searchRef.current) searchRef.current.click();
  };

  const options = {
    reset: {
      func: ({ id: userId }) => resetPasswords({ userId }),
      callback(res) {
        Modal.success({
          title: '默认密码已重置:',
          content: <Paragraph copyable>{res}</Paragraph>,
        });
      },
    },
    changeState: {
      func: ({ userState, id: userIds }) =>
        updateUserState({ state: userState ? '0' : '1', userIds }),
      callback: (_, row) => {
        message.success(row.userState ? '启用成功!' : '禁用成功!');
        reloadTable();
      },
    },
    unlock: {
      func: ({ id: userIds }) => updateUserLockState({ userIds }),
      callback: () => {
        message.success('解锁成功!');
        reloadTable();
      },
    },
    edit: {
      func: row => {
        setEditUser(row);
        setEditVisible(true);
        return Promise.resolve(true);
      },
      callback: () => { },
    },
  };

  const optionHandle = function optionHandle(key, row) {
    options[key].func(row).then(res => options[key].callback(res, row));
  };

  const columns = [
    {
      title: '头像',
      dataIndex: 'photo',
      hideInSearch: true,
      fixed: 'left',
      width: 100,
      render(_, row) {
        return (
          <Avatar
            shape="square"
            icon={row.photo ? false : 'user'}
            src={row.photo ? `data:image/png;base64,${row.photo}` : false}
          />
        );
      },
    },
    {
      title: '工号',
      dataIndex: 'userId',
      valueType: 'text',
      fixed: 'left',
      width: 100,
    },
    {
      title: '操作',
      valueType: 'option',
      dataIndex: 'id',
      fixed: 'left',
      width: 100,
      hideInTable: !(
        AuthComponent.getAuth('user.index.view') ||
        AuthComponent.getAuth('user.index.edit') ||
        AuthComponent.getAuth('user.index.enable_disable') ||
        AuthComponent.getAuth('user.index.unlock') ||
        AuthComponent.getAuth('user.index.reset')
      ),
      render: (text, row) => [
        <AuthComponent authCode="user.index.view">
          <Button
            onClick={() => {
              setCurrentUser(row);
              setDetailVisible(true);
            }}
            type="link"
            style={{ padding: 0 }}
          >
            查看
          </Button>
        </AuthComponent>,
        <TableDropdown
          onSelect={key => optionHandle(key, row)}
          menus={[]
            .concat(AuthComponent.getAuth('user.index.edit') ? [{ key: 'edit', name: '编辑' }] : [])
            .concat(
              AuthComponent.getAuth('user.index.enable_disable')
                ? [
                  {
                    key: 'changeState',
                    name: row.userState ? '启用' : '禁用',
                  },
                ]
                : [],
            )
            .concat(
              AuthComponent.getAuth('user.index.unlock') ? [{ key: 'unlock', name: '解锁' }] : [],
            )
            .concat(
              AuthComponent.getAuth('user.index.reset') ? [{ key: 'reset', name: '重置密码' }] : [],
            )}
        />,
      ],
    },
    {
      title: '姓名',
      dataIndex: 'tuCname',
      valueType: 'text',
      fixed: 'left',
      width: 100,
    },
    {
      title: '所在部门',
      dataIndex: 'deptName',
      hideInSearch: true,
    },
    {
      title: '职位',
      dataIndex: 'position',
      hideInSearch: true,
    },
    {
      title: '联系电话',
      dataIndex: 'tuMobile',
      hideInSearch: true,
    },
    {
      title: '邮箱地址',
      dataIndex: 'tuEmail',
      hideInSearch: true,
    },
    {
      title: '用户状态',
      dataIndex: 'userState',
      initialValue: '',
      valueEnum: {
        '': { text: '全部', status: 'Default' },
        '0': { text: '启用', status: 'Success' },
        '1': { text: '禁用', status: 'Default' },
      },
    },
    {
      title: '锁定状态',
      dataIndex: 'userLockState',
      initialValue: '',
      valueEnum: {
        '0': { text: '正常', status: 'Success' },
        '1': { text: '锁定', status: 'Default' },
      },
      hideInSearch: true,
    },
    {
      title: '上次登录时间',
      dataIndex: 'loginDate',
      hideInSearch: true,
    },
    {
      title: '最后修改时间',
      dataIndex: 'modifiDate',
      hideInSearch: true,
    },
  ];

  const { run: runSyncUser } = useRequest(manualSyncUser, {
    manual: true,
    onSuccess() {
      message.success('同步成功！');
      reloadTable();
    },
  });

  const [dept, setDept] = useState({});
  const [inited, setInited] = useState(false);
  useEffect(() => {
    if (!inited) {
      setInited(true);
    } else {
      reloadTable();
    }
  }, [dept.id, inited]);

  const [treeTitle, setTreeTitle] = useState('');

  const { loading, data = [] } = useRequest(getDepartmentTreeByRole, {
    onSuccess: ([root]) => {
      setTreeTitle(root.title);
      setSelectedKeys([root.key]);
      setDept(root);
    },
  });

  const onSelect = function onSelect(keys, { selected, node }) {
    setDept(node.props.dataRef ? node.props.dataRef : node.props);
    if (selected) {
      setSelectedKeys(keys);
    }
  };

  const onDetailClose = function onDetailClose() {
    setDetailVisible(false);
    setCurrentUser(false);
  };

  return (
    <section id="pageViewId" className={styles.wrapper}>
      <Tabs className={styles.treeWrapper}>
        <Tabs.TabPane tab={treeTitle} key="1">
          <Spin spinning={loading}>
            <TreeControlled
              className={styles.tree}
              selectable
              data={data}
              selectedKeys={selectedKeys}
              setSelectedKeys={onSelect}
            />
          </Spin>
        </Tabs.TabPane>
      </Tabs>

      <div className={`${styles.table} rest-pro-table-form-compact`}>
        <ProTable
          className={`rest-pro-table-form-compact ${isCollapse ? 'closeIndexTable' : 'indexTable'}`}
          scroll={{ x: 1200, y: height }}
          pagination={{
            showSizeChanger: true,
            showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
          }}
          options={{density:false,fullScreen:true, reload:false, setting:true}}
          search={{
            searchText: (
              <span ref={searchRef} href>
                查询
              </span>
            ),
            onCollapse: val => {
              controlC(val);
            }
          }}
          size='small'
          headerTitle={
            <span style={{ paddingRight: 10, fontWeight: 'bold', color: '#000' }}>
              {dept.title}
            </span>
          }
          rowKey="id"
          // toolBarRender={() => [
          //   <AuthComponent authCode="user.index.sync">
          //     <Button type="primary" onClick={() => runSyncUser()}>
          //       <Icon type="reload" />
          //       手动同步
          //     </Button>
          //   </AuthComponent>,
          // ]}
          request={params =>
            dept.id ? getUserList({ ...params, deptId: dept.id }) : Promise.resolve([])
          }
          columns={columns}
        />
      </div>
      {currentUser && detailVisible && (
        <Detail
          visible={detailVisible}
          onOption={optionHandle}
          onClose={onDetailClose}
          current={currentUser}
        />
      )}
      {editUser && editVisible && (
        <Edit
          visible={editVisible}
          data={editUser}
          onSuccess={() => reloadTable()}
          onClose={() => setEditVisible(false)}
        />
      )}
    </section>
  );
};

export default Form.create()(TableList);
